package com.hpjpw.idoapp.controller;

import com.hpjpw.ido.domain.*;
import com.hpjpw.ido.service.*;
import com.hpjpw.idoapp.domain.TaskSubmitVo;
import com.hpjpw.idoapp.service.IDoTaskService;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @BelongsProject: ruoyi
 * @BelongsPackage: com.hpjpw.idoapp.controller
 * @Author: hpj
 * @CreateTime: 2021-01-07 08:47
 * @Description: 实习宝藏任务模块
 */
@Api("实习宝藏任务模块Controller")
@RestController
@RequestMapping("/ido/app/task")
public class IDoTaskController extends BaseController {

    @Autowired
    private ITaskService taskService;

    @Autowired
    private IDoTaskService iDoTaskService;

    @Autowired
    private IWorkerService workerService;

    @Autowired
    private IStudentService studentService;

    @Autowired
    private ITaskRecordService taskRecordService;

    @Autowired
    private IStudentWorkerService studentWorkerService;

    /**
     * 获取实习宝藏任务详细信息
     */
    @GetMapping(value = "/{id}")
    @ApiOperation("获取实习宝藏任务详细信息")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return AjaxResult.success(taskService.selectTaskById(id));
    }

    /**
     * 获取实习宝藏任务星星数目总数
     */
    @GetMapping(value = "/getStarSumNum")
    @ApiOperation("获取实习宝藏任务星星数目总数")
    public AjaxResult getStarSumNum() {
        AjaxResult success = AjaxResult.success();
        success.put("num", taskRecordService.selectStarNumByStudentUserId(SecurityUtils.getUserId()));
        return success;
    }

    /**
     * 查询实习宝藏任务列表
     */
    @GetMapping("/student/list")
    @ApiOperation("查询实习宝藏任务列表")
    public TableDataInfo list() {
        startPage();
        List<Task> list = taskService.selectTaskList(new Task());
        return getDataTable(list);
    }

    /**
     * 通过任务ID领取实习宝藏任务
     */
    @PostMapping("/student/{taskId}")
    @ApiOperation("通过任务ID领取实习宝藏任务")
    public AjaxResult taskReceive(@PathVariable("taskId") Long taskId) {
        TaskRecord taskRecord = new TaskRecord();
        taskRecord.setStudentId(SecurityUtils.getUserId());
        taskRecord.setTaskId(taskId);
        taskRecord.setState(0L);
        List<TaskRecord> taskRecords = taskRecordService.selectTaskRecordList(taskRecord);
        if (StringUtils.isNotNull(taskRecords) && !taskRecords.isEmpty()) {
            return AjaxResult.error("您该任务还在进行中，不能领取该任务！");
        }
        taskRecord.setTime(new Date());
        taskRecord.setStar(0L);
        taskRecordService.insertTaskRecord(taskRecord);
        return AjaxResult.success("任务领取成功！");
    }

    /**
     * 查询实习宝藏任务记录列表
     */
    @GetMapping("/student/taskRecord/list")
    @ApiOperation("查询实习宝藏任务记录列表")
    public TableDataInfo taskRecordList() {
        TaskRecord taskRecord = new TaskRecord();
        taskRecord.setStudentId(SecurityUtils.getUserId());
        startPage();
        List<TaskRecord> list = taskRecordService.selectTaskRecordList(taskRecord);
        return getDataTable(list);
    }

    /**
     * 通过任务记录ID提交审核实习宝藏任务
     */
    @PutMapping("/student/{taskRecordId}")
    @ApiOperation("通过任务记录ID提交审核实习宝藏任务")
    public AjaxResult taskSubmit(@PathVariable("taskRecordId") String taskRecordId, @RequestBody TaskSubmitVo taskSubmitVo) {
        TaskRecord taskRecord = taskRecordService.selectTaskRecordById(taskRecordId);
        if (StringUtils.isNull(taskRecord) || !taskRecord.getStudentId().equals(SecurityUtils.getUserId()))
            return AjaxResult.error("找不到该任务记录");
        taskRecord.setState(1L);
        taskRecord.setPicture(taskSubmitVo.getPicture());
        taskRecord.setDescribe(taskSubmitVo.getDescribe());
        taskRecord.setTime(new Date());
        taskRecordService.updateTaskRecord(taskRecord);
        return AjaxResult.success("任务提交审核！");
    }

    /**
     * 查询可审核的实习宝藏任务记录列表
     */
    @GetMapping("/worker/taskRecord/list")
    @ApiOperation("查询可审核的实习宝藏任务记录列表")
    public TableDataInfo workerTaskRecordList() {
        if (!iDoTaskService.isWorker())
            return getDataTable(new ArrayList<>());
        StudentWorker studentWorker_q = new StudentWorker();
        studentWorker_q.setWorkerUserId(SecurityUtils.getUserId());
        List<StudentWorker> studentWorkerList = studentWorkerService.selectStudentWorkerList(studentWorker_q);
        if (studentWorkerList.size() <= 0)
            return getDataTable(new ArrayList<>());
        Long[] studentIds = new Long[studentWorkerList.size()];
        for (int i = 0; i < studentWorkerList.size(); i++) {
            studentIds[i] = studentWorkerList.get(i).getStudentUserId();
        }
        startPage();
        List<TaskRecord> taskRecords = taskRecordService.selectTaskRecordByStudentIdsWithUnchecked(studentIds);
        return getDataTable(taskRecords);
    }

    /**
     * 获取实习宝藏任务记录
     */
    @GetMapping("/worker/{taskRecordId}")
    @ApiOperation("获取实习宝藏任务记录")
    public AjaxResult workerGetTask(@PathVariable("taskRecordId") String taskRecordId) {
        if (!iDoTaskService.isWorker())
            return AjaxResult.error("无此权限！");

        TaskRecord taskRecord = taskRecordService.selectTaskRecordById(taskRecordId);
        if (StringUtils.isNull(taskRecord))
            return AjaxResult.error("找不到该记录");

        StudentWorker studentWorker_q = new StudentWorker();
        studentWorker_q.setWorkerUserId(SecurityUtils.getUserId());
        studentWorker_q.setStudentUserId(taskRecord.getStudentId());
        List<StudentWorker> list = studentWorkerService.selectStudentWorkerList(studentWorker_q);
        if (StringUtils.isNull(list) || list.isEmpty())//返回的列表为空即代表该企业员工并未与该条任务记录的学生建立关联
            return AjaxResult.error("无此权限！");

        return AjaxResult.success(taskRecord);
    }

    /**
     * 审核实习宝藏任务记录
     */
    @PostMapping("/worker/{taskRecordId}")
    @ApiOperation("审核实习宝藏任务记录")
    @Log(title = "审核实习宝藏任务记录", businessType = BusinessType.UPDATE)
    public AjaxResult workerTaskCheck(@PathVariable("taskRecordId") String taskRecordId, Long starNum) {
        if (!iDoTaskService.isWorker())
            return AjaxResult.error("无此权限！");

        TaskRecord taskRecord = taskRecordService.selectTaskRecordById(taskRecordId);
        if (StringUtils.isNull(taskRecord))
            return AjaxResult.error("找不到该记录");

        StudentWorker studentWorker_q = new StudentWorker();
        studentWorker_q.setWorkerUserId(SecurityUtils.getUserId());
        studentWorker_q.setStudentUserId(taskRecord.getStudentId());
        List<StudentWorker> list = studentWorkerService.selectStudentWorkerList(studentWorker_q);
        if (StringUtils.isNull(list) || list.isEmpty())//返回的列表为空即代表该企业员工并未与该条任务记录的学生建立关联
            return AjaxResult.error("无此权限！");

        Task task = taskService.selectTaskById(taskRecord.getTaskId());
        if (starNum > task.getStar()) {
            taskRecord.setStar(task.getStar());
        } else {
            taskRecord.setStar(starNum);
        }

        taskRecord.setTime(new Date());
        taskRecord.setStar(starNum);
        taskRecord.setState(2L);
        taskRecordService.updateTaskRecord(taskRecord);

        return AjaxResult.success("审核成功");
    }

    /**
     * 查询可关联的学生列表
     */
    @GetMapping("/worker/students")
    @ApiOperation("查询可关联的学生列表")
    public TableDataInfo workerStudentList() {
        Worker worker = workerService.selectWorkerByUserId(SecurityUtils.getUserId());
        if (StringUtils.isNull(worker))
            return getDataTable(new ArrayList<>());
        Student student_q = new Student();
        student_q.setEnterpriseId(worker.getEnterpriseId());
        startPage();
        List<Student> students = studentService.selectStudentList(student_q);
        return getDataTable(students);
    }

    /**
     * 查询已关联的学生列表
     */
    @GetMapping("/worker/students/list")
    @ApiOperation("查询已关联的学生列表")
    public TableDataInfo workerAndStudentList() {
        Worker worker = workerService.selectWorkerByUserId(SecurityUtils.getUserId());
        if (StringUtils.isNull(worker))
            return getDataTable(new ArrayList<>());

        List<Student> students = new ArrayList<>();

        StudentWorker studentWorker_q = new StudentWorker();
        studentWorker_q.setWorkerUserId(SecurityUtils.getUserId());
        List<StudentWorker> studentWorkerList = studentWorkerService.selectStudentWorkerList(studentWorker_q);
        for (StudentWorker studentWorker : studentWorkerList) {
            Student student = studentService.selectStudentByUserID(studentWorker.getStudentUserId());
            if (StringUtils.isNotNull(student))
                students.add(student);
        }
        return getDataTable(students);
    }

    /**
     * 通过学生的学生ID关联学生
     */
    @PostMapping("/worker/student/{studentId}")
    @ApiOperation("通过学生的学生ID关联学生")
    @Log(title = "关联学生", businessType = BusinessType.INSERT)
    public AjaxResult AddWorkerStudent(@PathVariable("studentId") Long studentId) {
        if (!iDoTaskService.isWorker())
            return AjaxResult.error("无此权限！");
        StudentWorker studentWorker_q = new StudentWorker();
        studentWorker_q.setStudentUserId(studentId);
        List<StudentWorker> studentWorkerList = studentWorkerService.selectStudentWorkerList(studentWorker_q);
        if (StringUtils.isNotNull(studentWorkerList) && !studentWorkerList.isEmpty())
            return AjaxResult.error("该学生已被关联！");
        StudentWorker studentWorker = new StudentWorker();
        studentWorker.setWorkerUserId(SecurityUtils.getUserId());
        studentWorker.setStudentUserId(studentId);
        studentWorker.setDatetime(new Date());
        studentWorkerService.insertStudentWorker(studentWorker);
        return AjaxResult.success("关联成功");
    }

    /**
     * 通过学生的学生ID取消关联学生
     */
    @DeleteMapping("/worker/student/{studentId}")
    @ApiOperation("通过学生的学生ID取消关联学生")
    @Log(title = "取消关联学生", businessType = BusinessType.DELETE)
    public AjaxResult DeleteWorkerStudent(@PathVariable("studentId") Long studentId) {
        if (!iDoTaskService.isWorker())
            return AjaxResult.error("无此权限！");

        StudentWorker studentWorker_q = new StudentWorker();
        studentWorker_q.setWorkerUserId(SecurityUtils.getUserId());
        studentWorker_q.setStudentUserId(studentId);
        List<StudentWorker> studentWorkerList = studentWorkerService.selectStudentWorkerList(studentWorker_q);

        if (StringUtils.isNull(studentWorkerList) || studentWorkerList.isEmpty())
            return AjaxResult.error("取消关联失败");
        for (StudentWorker studentWorker : studentWorkerList) {
            studentWorkerService.deleteStudentWorkerById(studentWorker.getId());
        }
        return AjaxResult.success("取消关联成功");
    }
}
